<?php defined('SYSPATH') or die('No direct script access.') ;
/**
 * 会员数据模型
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: member.php 269 2012-06-25 07:22:54Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Model_Member extends Model
{

    /**
     * members 表字段
     *
     * @var array
     */
    protected $_member_fields = array(
        'email', 'nickname', 'password', 'reg_time', 'reg_ip',
        'last_time', 'last_ip', 'last_failed', 'failed_nums', 'status',
    );

    /**
     * 获取所有会员列表
     *
     * @return array
     */
    public function all_sql()
    {
        return DB::select()
            ->from('members');
    }

    /**
     * 获取会员信息
     *
     * @param  int  $member_id
     * @return array
     */
    public function get($member_id)
    {
        return Member::get($member_id);
    }

    /**
     * 修改会员资料
     *
     * @param  int    $member_id
     * @param  array  $data
     * @return bool
     */
    public function profile($member_id, array $data)
    {
        $v = Validation::factory($data)
            ->rule('password', 'min_length', array(':value', '6'))
            ->rule('confirm', 'matches', array(':validation', ':field', 'password'))
            ->rule('nickname', 'not_empty')
            ->rule('nickname', 'min_length', array(':value', '2'))
            ->rule('nickname', 'max_length', array(':value', '20'))
            ->rule('nickname', 'regex', array(':value', '/^[^\'\"\:;,\<\>\?\/\\\*\=\+\{\}\[\]\)\(\^%\$#\!`\s]+$/'))
            ->rule('nickname', array($this, 'nick_unique'), array(':value', $member_id))
            ->rule('status', 'not_empty')
            ->rule('status', 'range', array(':value', -1, 1));

        $this->validation($v);
        if ( ! $v->check())
        {
            return FALSE;
        }

        $data = $v->as_array();
        $member = array();
        $fields = array('member_id' => $member_id);
        foreach ($data as $key => $value)
        {
            if (in_array($key, $this->_member_fields))
            {
                if ($key == 'password')
                {
                    $value AND $member[$key] = Password::create($value);
                }
                else
                {
                    $member[$key] = $value;
                }
            }
        }

        // 更新会员表
        DB::update('members', $member)->where('member_id', '=', $member_id)->execute();

        return TRUE;
    }

    /**
     * 检测昵称是否重复
     *
     * @param  string  $nickname
     * @param  int     $member_id
     * @return bool
     */
    public function nick_unique($nickname, $member_id)
    {
        return ! (bool) DB::select()
            ->from('members')
            ->where('nickname', '=', $nickname)
            ->where('member_id', '<>', $member_id)
            ->count_all();
    }

}